const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

const fs = require('fs')

const multer = require('koa-multer'); //加载koa-multer模块

//文件上传
//配置
var storage = multer.diskStorage({
        //文件保存路径
        destination: function(req, file, cb) {
            cb(null, 'public/uploads/')
        },
        //修改文件名称
        filename: function(req, file, cb) {
            var fileFormat = (file.originalname).split(".");
            cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
        }
    })
    //加载配置
var upload = multer({ storage: storage });

const Router = require('koa-router');
const router = new Router();

function htmlvg() {
    return new Promise((resolve, reject) => {
        fs.readFile('./upload.html', (err, data) => {
            if (err) throw err;
            let html = data.toString()
            resolve(html)
        });
    })

}

router.get('/', async function(ctx, next) {

    ctx.body = await htmlvg()
    next()

});


router.post('/upload', upload.single('file'), async(ctx, next) => {
    ctx.body = {
        filename: ctx.req.file.filename //返回文件名
    }
    next()
})



router.post('/hehe', async(ctx, next) => {
    ctx.body = {
        msg: "呵呵哒" //返回文件名
    }
})


app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')